/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.apps.controllers;

/**
 *
 * @author ARIJIT PAL
 */
import com.jcraft.jsch.Channel;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.List;
import java.util.Map;


public class CustomInputStream extends InputStream {

	private String command;
        private String id;
	private int count;
	private boolean flag;
	private int time;
        private CmdOutController cmdOutController;
        private Thread th;

	public CustomInputStream(int time, Channel channel) throws Exception{
            this.time = time;
            try {
                DBController.updateData("drop table if exists commandio;");
                String sql = "CREATE TABLE IF NOT EXISTS \"commandio\" ( "
                + "\"id\" TEXT PRIMARY KEY,"
                + "\"command\" TEXT,"
                + "\"flag\" TEXT,"
                + "\"output\" TEXT)";
                DBController.updateData(sql);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            cmdOutController = new CmdOutController(channel);
            flag = true;
	}

        public void startCmdOut(){
            th = new Thread(cmdOutController);
            th.start();
        }

        public CmdOutController getCmdOutController(){
            return cmdOutController;
        }

	@Override
	public int read() throws IOException {
            try{
                int pingCount=0;
                //cmdOutController.setChannelFlag(true);
                while(command==null) {
                    String sql = "select * from commandio where flag='I' ";
                    List<Map<String, Object>> rs = DBController.getResult(sql);
                    if(!rs.isEmpty()){
                        command = (String)rs.get(0).get("command")+"\n";
                        count = 0;
                        id = (String)rs.get(0).get("id");
                        sql = "update commandio set flag='R' where id='"+id+"' ";
                        DBController.updateData(sql);
                    }else{
                        try{Thread.currentThread().sleep(500);}catch(Exception ex){ex.printStackTrace();}
                        if(pingCount++ > time*2){
                            command = "pwd\n";
                            count = 0;
			}
                    }
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }

            if(command != null){
                if (count < command.length()) {
                        char c = command.charAt(count++);
                        return c;
                }
            }
            command = null;
            return -1;
	}

	public synchronized boolean setCommand(String command){
		//System.out.println("<" + command + ">");
		if(flag){
			command += "\n";
			this.command = command;
			count = 0;
			return true;
		}
		return false;
	}
        
        public String insertCommand(String command) throws Exception{
            Calendar cal = Calendar.getInstance();
            String id = cal.getTimeInMillis() + "CMD" + (int)(Math.random()*10000) + command.toUpperCase().split(" ")[0];
            String flag = "X";//I=input; O=output; R=received; X=None;
            String sql = "INSERT INTO commandio VALUES ('"+id+"','"+command+"','"+flag+"',' ')";
            int i = DBController.updateData(sql);
            if(i==1)
                return id;
            else
                return null;
        }

        public String getOutput(String command, int timeOut, String endStr)throws Exception{
            String idL = insertCommand(command);
            id = idL;
            cmdOutController.setFlag(false);
            cmdOutController.setListener(endStr, idL);
            DBController.updateData("update commandio set flag='I' where id='"+id+"' ");
            int countL = 0;
            while(countL<=timeOut){
                String sql = "select * from commandio where flag='O' and id='"+id+"' ";
                List<Map<String, Object>> rs = DBController.getResult(sql);
                if(!rs.isEmpty()){
                    String output = (String)rs.get(0).get("output");
                    return output;
                }
                try{Thread.currentThread().sleep(1000);}catch(Exception ex){}
                if(timeOut != 0){
                    countL+=(1000-1);
                }
            }
            //timeout
            DBController.updateData("update commandio set output = 'timeout', flag='O' where id='"+id+"' ");
            cmdOutController.setFlag(true);
            return null;
        }
}
